//
//  GradientView.m
//  QiBaoTong
//
//  Created by 韩艳锋 on 2019/6/18.
//  Copyright © 2019 策驭. All rights reserved.
//

#import "GradientView.h"
#import "NSArray+hf.h"


@implementation GradientView{
    GradientViewDirection direction;
    NSArray<UIColor*>* _colors;
    CAGradientLayer* gradientLayer;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        gradientLayer = [[CAGradientLayer alloc] init];
        _gradientEnable = YES;
        [self.layer addSublayer:gradientLayer];
    }
    return self;
}

-(CGPoint)starPoint {
    if (direction == horizontal) {
//        return CGPointMake(0, CGRectGetMidY(self.bounds));
        
    }
    return CGPointMake(0, 0);
}

-(CGPoint)endPoint {
    if (direction == horizontal) {
//        return CGPointMake(CGRectGetMaxX(self.bounds), CGRectGetMidY(self.bounds));
        return CGPointMake(1, 0);
    } else {
        return CGPointMake(0, 1);
    }
}

-(void)setHorizontalBalanceGradien:(NSArray<UIColor*>*)colors{
    direction = horizontal;
    _colors = colors;
    [self setNeedsLayout];
}

-(void)setVerticalBalanceGradien:(NSArray<UIColor*>*)colors{
    direction = vertical;
    _colors = colors;
    [self setNeedsLayout];
}

-(void)layoutSubviews {
    
    [self upDateGradien];
}

-(void)upDateGradien{
    
    if (self.bounds.size.width == 0 || self.bounds.size.height == 0) return;
    gradientLayer.frame = self.layer.bounds;
    [gradientLayer setStartPoint:[self starPoint]];
    [gradientLayer setEndPoint:[self endPoint]];
    
//    if (direction == horizontal) {
//        NSMutableArray * loca = [NSMutableArray arrayWithCapacity:_colors.count];
//        NSInteger num = _colors.count;
//        for (double i = 1; i != num + 1; i++) {
//            [loca addObject:[NSNumber numberWithDouble:i / (num + 1)]];
//        }
//        gradientLayer.locations = [loca copy];
//    }
    
    [gradientLayer setColors: [_colors map:^ id (UIColor* _Nonnull obj) {
        return (id)obj.CGColor;
    }]];
}

-(void)setGradientEnable:(BOOL)gradientEnable {
    if (gradientEnable) {
        [self.layer insertSublayer:gradientLayer atIndex:0];
    } else {
        [gradientLayer removeFromSuperlayer];
    }
    _gradientEnable = gradientEnable;
}
@end
